package hn.cch.advanced.concurrent;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * ForkJoinPool用来解决父子任务有依赖的并行计算问题
 */
public class ForkJoinPoolDemo {

    private static final Logger logger = LoggerFactory.getLogger(ForkJoinPoolDemo.class);


    public static void main(String[] args) {
        // ForkJoinPool forkJoinPool = new ForkJoinPool(4);
        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        logger.debug("start");
        Integer result = forkJoinPool.invoke(new Fibonacci(10));
        logger.debug("stop:{}", result);

        forkJoinPool.shutdown();

    }

    /**
     * 递归任务：斐波那契Fibonacci
     */
    static class Fibonacci extends RecursiveTask<Integer> {

        Integer number;

        Fibonacci(Integer number) {
            this.number = number;
        }


        @Override
        protected Integer compute() {

            if (number <= 1) { // 递归结束条件
                return 1;
            }
            Fibonacci fibonacci1 = new Fibonacci(number - 1);
            fibonacci1.fork();
            Fibonacci fibonacci2 = new Fibonacci(number - 2);
            Integer result = fibonacci2.compute() + fibonacci1.join();
            logger.debug("{}={}", number, result);
            return result;
        }
    }

}
